package info.cs52.fes.action.auth;

import info.cs52.fes.FesAction;
import info.cs52.fes.action.SessionUtils;
import info.cs52.fes.dao.UserDAO;
import info.cs52.fes.data.User;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class RegisterAction extends FesAction {

	private User userInfo;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		userInfo = new User();
	
		UserService userService = UserServiceFactory.getUserService();
		com.google.appengine.api.users.User gUser = userService.getCurrentUser();
		if (gUser != null) {
			User user = UserDAO.findByServiceUserId(gUser.getUserId());
			if (user != null) {
				SessionUtils.login(req, user);
				String returnUrl = "/" + getServletContext().getContextPath();
				resp.sendRedirect(returnUrl);
			}
			userInfo.setServiceUserId(gUser.getUserId());
			userInfo.setEmail(gUser.getEmail());
			userInfo.setName(gUser.getNickname());
		}
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		if (!"register".equals(req.getParameter("submit")) || !validate(req)) {
			return;
		}
		User user = new User();
		
		UserService userService = UserServiceFactory.getUserService();
		com.google.appengine.api.users.User gUser = userService.getCurrentUser();
		if (gUser == null) {
			resp.sendRedirect(userService.createLoginURL(req.getRequestURI()));
		}
		user.setServiceUserId(gUser.getUserId());
		user.setEmail(gUser.getEmail());

		user.setName(req.getParameter("name"));
		
		UserDAO.persist(user);
		SessionUtils.login(req, user);
		
		String returnUrl = req.getParameter("returnUrl");
		if (returnUrl == null) {
			returnUrl = "/" + getServletContext().getContextPath();
		}
		resp.sendRedirect(returnUrl);
	}
	
	private boolean validate(HttpServletRequest req) {
		if (StringUtils.isEmpty(req.getParameter("name"))) {
			message = "Tên người dùng là bắt buộc";
			return false;
		}
		return true;
	}

	public User getUserInfo() {
		return userInfo;
	}
	
}
